package net.softwarefabrik.bde.core.model.maven;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;

/*import org.apache.maven.embedder.Configuration;
import org.apache.maven.embedder.ConfigurationValidationResult;
import org.apache.maven.embedder.DefaultConfiguration;
import org.apache.maven.embedder.MavenEmbedder;
import org.apache.maven.embedder.MavenEmbedderConsoleLogger;
import org.apache.maven.embedder.MavenEmbedderException;
import org.apache.maven.execution.DefaultMavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.execution.MavenExecutionResult;
*/
public final class MavenCommand {

    @SuppressWarnings("unchecked")
	public static void run(File projectDirectory, String goal) {

    	try {
			Process process = Runtime.getRuntime().exec("mvn " + goal, null, projectDirectory);
			BufferedOutputStream os = new BufferedOutputStream(process.getOutputStream());
			int result = process.waitFor();
			if (result > 0) {
				System.out.println("BDE - " + "error running mvn: " + result);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
/*		Configuration configuration = new DefaultConfiguration();
		configuration.setGlobalSettingsFile(new File("/usr/share/maven/conf", "settings.xml"));
		configuration.setUserSettingsFile(MavenEmbedder.DEFAULT_USER_SETTINGS_FILE);
		configuration.setClassLoader(Thread.currentThread()
										   .getContextClassLoader());
		configuration.setMavenEmbedderLogger(new MavenEmbedderConsoleLogger());
		//
		ConfigurationValidationResult validationResult = MavenEmbedder.validateConfiguration(configuration);

	    if (validationResult.isValid()) {
	    	
			try {
//				ClassLoader orig = Thread.currentThread().getContextClassLoader();
//			    ClassLoader loader = MavenEmbedder.class.getClassLoader();
//			    Thread.currentThread().setContextClassLoader(loader);
				MavenEmbedder embedder = new MavenEmbedder(configuration);
//				Thread.currentThread().setContextClassLoader(orig);

				MavenExecutionRequest request = new DefaultMavenExecutionRequest();
				request.setPomFile(new File(projectDirectory, "pom.xml").getAbsolutePath());
				request.setShowErrors(true);
			    request.setUseReactor(false);
			    request.setRecursive(true);
				request.setBaseDirectory(projectDirectory);
				request.setGoals(Arrays.asList(goals.split(",")));
				// request.setWorkspaceMonitor();

				MavenExecutionResult result = embedder.execute(request);

				if (result.hasExceptions()) {
					for (Exception e : (Collection<Exception>)result.getExceptions()) {
						e.printStackTrace();
					}
				}
			} catch (MavenEmbedderException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
*/	}
}
